package com.bj.disc.util

import android.content.Context
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.util.Base64
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.util.concurrent.ArrayBlockingQueue


class AndroidMessagePlayer(private val context: Context) {

    private val mainHandler = Handler(Looper.getMainLooper())
    private val mediaPlayer: MediaPlayer = MediaPlayer()
    private val messageQueue = ArrayBlockingQueue<String>(Int.MAX_VALUE)

    init {
        configurePlayer()
        setupPlayerListener()
    }

    private fun configurePlayer() {
        // 配置音频播放相关参数
        val audioAttributes = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
        mediaPlayer.setAudioAttributes(audioAttributes)
    }

    private fun setupPlayerListener() {
        mediaPlayer.setOnCompletionListener {
            // 播放完成，播放下一个消息
            playNextMessage()
        }
    }

    fun start() {
        // 开始播放第一个消息
        playNextMessage()
    }

    fun handleMessage(base64Data: String) {
        // 处理收到的消息，将其加入消息队列
        messageQueue.offer(base64Data)

        // 如果当前没有正在播放的消息，开始播放
        if (!mediaPlayer.isPlaying) {
            playNextMessage()
        }
    }

    private fun playNextMessage() {
        val nextMessage = messageQueue.poll()

        if (nextMessage != null) {
            // 使用协程异步进行播放
            GlobalScope.launch(Dispatchers.IO) {
                playBase64Audio(nextMessage)
            }
        }
    }

    private fun playBase64Audio(base64Data: String) {
        try {
            // 将 base64 数据解码为字节数组
            val audioData = Base64.decode(base64Data, Base64.DEFAULT)
            val url = "data:audio/mp3;base64,$audioData"
            val uri = Uri.parse(url)
            // 设置 MediaPlayer 数据源
            mediaPlayer.reset()
            mediaPlayer.setDataSource(context,uri)
            // 准备并开始播放
            mediaPlayer.prepare()
            mediaPlayer.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun pause() {
        if (mediaPlayer.isPlaying) {
            mediaPlayer.pause()
        }
    }

    fun release() {
        // 释放资源
        mediaPlayer.release()
    }
}

